import sys
sys.path.append('F:\\python36\\Lib\\site-packages')

from serialization import serialize
from putData2redis import putStreamIntoRedis


import time,threading
from PIL import ImageGrab
from cv2 import *
import numpy as np
from pynput import keyboard

def video_record():   # 录入视频
  screen = ImageGrab.grab() # 获取当前屏幕
  width, high = screen.size # 获取当前屏幕的大小
  # fourcc = VideoWriter_fourcc('X', 'V', 'I', 'D') # MPEG-4编码,文件后缀可为.avi .asf .mov等
  # video = VideoWriter('./videoFlow.avi', fourcc, 15, (width, high)) # （文件名，编码器，帧率，视频宽高）

  print('开始直播!(按Home建结束)')
  INTERVAL=5
  count=0
  ims=[]
  while True:
    if flag:
      print("直播结束！")
      global final_time
      final_time = time.time()
      # video.release() #释放
      break
    im = ImageGrab.grab()  # 图片为RGB模式
    
    ims.append(np.array(im))
    # imm = cvtColor(np.array(im), COLOR_RGB2BGR) # 转为opencv的BGR模式
    # video.write(imm)  #写入
    if(count>=INTERVAL):
          count=0
          datastream=serialize(ims)
          putStreamIntoRedis("xiaohao",datastream)
          ims=[]
    count+=1
          
def on_press(key):   # 监听按键
  global flag
  if key == keyboard.Key.home:
    flag = True # 改变
    return False # 返回False，键盘监听结束！

if __name__ == '__main__':
  flag = False
  th = threading.Thread(target=video_record)
  th.start()
  with keyboard.Listener(on_press=on_press) as listener:
    listener.join()